﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace StopWatch
{
    public partial class StopWatch : Form
    {

        [DllImport("Kernel32.dll")]
        public static extern bool Beep(UInt32 frequency, UInt32 duration);

        TimeSpan myTime;
        Timer timer = new Timer();
        public StopWatch()
        {
            InitializeComponent();
            myTime = new TimeSpan(0, 0, 0, 0, 0);
            
            timer.Interval = 100;
            timer.Tick += new EventHandler(timer_Tick);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            myTime = myTime.Add(TimeSpan.FromMilliseconds(100));
            timeLabel.Text = myTime.Hours.ToString("D2") + ":" + myTime.Minutes.ToString("D2") + ":" + myTime.Seconds.ToString("D2") + "." + (myTime.Milliseconds == 0 ? "0" : myTime.Milliseconds.ToString("D2").Trim('0'));
        }


        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //Called whenever a key is pressed
            if (timer.Enabled)
            {
                Beep(500, 300);
                timer.Stop();
                startToolStripMenuItem.Enabled = true;
                stopToolStripMenuItem.Enabled = false;
            }
            else
            {
                Beep(500, 300);
                timer.Start();
                startToolStripMenuItem.Enabled = false;
                stopToolStripMenuItem.Enabled = true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Beep(500, 300);
            timer.Start();
            startToolStripMenuItem.Enabled = false;
            stopToolStripMenuItem.Enabled = true;
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Beep(500, 300);
            timer.Stop();
            startToolStripMenuItem.Enabled = true;
            stopToolStripMenuItem.Enabled = false;
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            myTime = new TimeSpan(0, 0, 0, 0, 0);
            timeLabel.Text = myTime.Hours.ToString("D2") + ":" + myTime.Minutes.ToString("D2") + ":" + myTime.Seconds.ToString("D2") + "." + (myTime.Milliseconds == 0 ? "0" : myTime.Milliseconds.ToString("D2").Trim('0'));
        }
    }
}
